//
//  XDVerifiedViewController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/2/23.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDVerifiedViewController.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "ZHRTBasicMethod.h"
#import "AFHTTPSessionManager+POST.h"
#import "XDSetSafePassViewController.h"
#import "XDBindBankCardViewController.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "XDToWithdrawViewController.h"
#define kAlphaNum @"Xx0123456789"
@interface XDVerifiedViewController ()<UITextFieldDelegate>

@property (nonatomic,weak) UITextField *nameTf;
@property (nonatomic,weak) UITextField *cardTf;
@property (nonatomic, weak) UIButton *nextBtn;

@property (nonatomic, weak) UIButton *agreeBtn;
@end

@implementation XDVerifiedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"实名认证";
    [self setUI];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(nameTextFeildEditChanged:)
                                                name:UITextFieldTextDidChangeNotification object:self.nameTf];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(nameTextFeildEditChanged:)
                                                name:UITextFieldTextDidChangeNotification object:self.cardTf];
}



//判断是否是数字，不是的话就输入失败
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    if (textField == self.cardTf) {
        
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    BOOL canChange = [string isEqualToString:filtered];
    if (!canChange) {
        
    [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入真实的身份证号码" view:self.view];
        
    }
    
    return canChange;
    }
    return YES;
}

- (void)nameTextFeildEditChanged:(id)notification{

    UITextRange *selectedRange = self.nameTf.markedTextRange;
    UITextPosition *position = [self.nameTf positionFromPosition:selectedRange.start offset:0];
    
    if (!position) { //// 没有高亮选择的字
        //过滤非汉字字符
        
        if (![ZHRTBasicMethod isChinese:self.nameTf.text] && self.nameTf.text.length > 0) {
            //
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入真实姓名(只支持中文)" view:self.view];
        }
        self.nameTf.text = [self filterCharactor:self.nameTf.text withRegex:@"[^\u4e00-\u9fa5]"];
    }else { //有高亮文字
        //do nothing
    }
    
    NSString *cardTfText = [[self.cardTf.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSMutableString *insertStr = [NSMutableString stringWithString:cardTfText];
    
    if (cardTfText.length > 18) {
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入真实的身份证号码" view:self.view];
        self.cardTf.text = [self.cardTf.text stringByReplacingCharactersInRange:NSMakeRange(self.cardTf.text.length - 1, 1) withString:@""];
        cardTfText = self.cardTf.text;
    }
    
    if (cardTfText.length == 18) {
        if (cardTfText.length > 6 || cardTfText.length > 14   ) {
            
            
            
            for (NSInteger i = 0; i < cardTfText.length; i ++) {
                if (i == 6) {
                    [insertStr insertString:@" " atIndex:6];
                }
                
                if (i == 14) {
                    [insertStr insertString:@" " atIndex:15];
                }
            }
            self.cardTf.text = insertStr;
        }
        

    } else {
        self.cardTf.text = cardTfText;
    }
  
    if (self.nameTf.text.length > 0 && self.cardTf.text.length > 14 && self.agreeBtn.selected) {
        self.nextBtn.enabled = YES;
    } else {
        self.nextBtn.enabled = NO;
    }
}

//根据正则，过滤特殊字符
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *searchText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
    return result;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setUI {
    
    UIView *view = [[UIView alloc] initWithFrame:kScreenB];
    view.backgroundColor = kColorRGB(234, 234, 234);
    [self.view addSubview: view];

    UIView *tipBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
    tipBackground.backgroundColor = kColorRGB(232,213,177);
    [view addSubview:tipBackground];
    
    UILabel *tipLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenW, 30)];
    tipLb.text = @"* 为确保账户资金安全,绑卡前请先进行实名认证";
    tipLb.textColor = kColorRGB(24,24,24);
    tipLb.font = kBaseFont_(12);

    [tipBackground addSubview:tipLb];

    UITextField *nameTf =  [self createTextFieldWithFrame:CGRectMake(0, CGRectGetMaxY(tipLb.frame) + 10, kScreenW, 50) textFont:kBaseFont_(16) textColor:kColorRGB(51, 51, 51) placeholder:@"请输入真实姓名" placeholderFont:kBaseFont_(13) leftTitle:@"姓名" delegate:self inView:view tag:0];
    self.nameTf = nameTf;
    
   UITextField *cardTf = [self createTextFieldWithFrame:CGRectMake(0, CGRectGetMaxY(nameTf.frame) + 10, kScreenW, 50) textFont:kFont_(16) textColor:kColorRGB(51, 51, 51) placeholder:@"请输入真实身份证号码" placeholderFont:kBaseFont_(13) leftTitle:@"身份证号" delegate:self inView:view tag:1];
    self.cardTf = cardTf;
    
    UIImage *img = [UIImage imageNamed:@"next_fill_hieght"];
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenW - img.size.width) * 0.5 ,CGRectGetMaxY(cardTf.frame) + 38 , img.size.width, img.size.height)];
    [nextBtn setBackgroundImage:img forState:UIControlStateNormal];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"next_fill_nor"] forState:UIControlStateDisabled];
    nextBtn.enabled = NO;
    [nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:nextBtn];
    self.nextBtn = nextBtn;
    
    
    UIView *dowmView = [[UIView alloc] initWithFrame:CGRectMake(65, CGRectGetMaxY(nextBtn.frame) + 20, kScreenW - 130, 20)];
    [view addSubview:dowmView];
    
    UIButton *agreeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 12)];
    [agreeBtn setBackgroundImage:[UIImage imageNamed:@"agree_yes"] forState:UIControlStateSelected];
    [agreeBtn setBackgroundImage:[UIImage imageNamed:@"agree_nor"] forState:UIControlStateNormal];
    agreeBtn.selected = YES;
    [agreeBtn addTarget:self action:@selector(agreeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.agreeBtn = agreeBtn;
    [dowmView addSubview:agreeBtn];
    
    UILabel *alreadyReadLab = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, 0, 0)];
    alreadyReadLab.text = @"我已阅读并同意";
    alreadyReadLab.font = kBaseFont_(12);
    alreadyReadLab.textColor = [UIColor grayColor];
    [alreadyReadLab sizeToFit];
    alreadyReadLab.frame = CGRectMake(CGRectGetMaxX(agreeBtn.frame) + 3, CGRectGetMidY(agreeBtn.frame) -  alreadyReadLab.frame.size.height * 0.5 , alreadyReadLab.frame.size.width, alreadyReadLab.frame.size.height);
    [dowmView addSubview:alreadyReadLab];
    
    UIButton *xindaiBtn = [[UIButton alloc] initWithFrame:CGRectMake(98, 0, 0, 0)];
    xindaiBtn.titleLabel.font = [UIFont systemFontOfSize:FONTSIZE12];
    [xindaiBtn setTitle:@"《新贷联盟实名认证协议》" forState:UIControlStateNormal];
    [xindaiBtn setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
    xindaiBtn.titleLabel.font = kBaseFont_(12);
    [xindaiBtn addTarget:self action:@selector(xindaiBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [xindaiBtn sizeToFit];
    xindaiBtn.frame = CGRectMake(CGRectGetMaxX(alreadyReadLab.frame), CGRectGetMidY(agreeBtn.frame) -  xindaiBtn.frame.size.height * 0.5, xindaiBtn.frame.size.width, xindaiBtn.frame.size.height);
    [dowmView addSubview:xindaiBtn];
    
    CGFloat downX = (kScreenW - (CGRectGetMaxX(xindaiBtn.frame) - CGRectGetMinX(agreeBtn.frame))) * 0.5;
    dowmView.frame = CGRectMake(downX, CGRectGetMaxY(nextBtn.frame) + 20, kScreenW - downX * 2, 20);
    
    
}

//修改UITextField的placeholder字体并垂直居中
- (NSAttributedString *)textFieldAttributedPlaceholderWith:(UITextField *)textField placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont  {
    NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - placeholderFont.lineHeight) / 2.0;
    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName:placeholderFont, NSParagraphStyleAttributeName : style}];
    return attr;
}

- (UITextField *)createTextFieldWithFrame:(CGRect)frame textFont:(UIFont *)textFont textColor:(UIColor *)textColor placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont leftTitle:(NSString *)leftTitle delegate:(id)obj inView:(UIView *)inView tag:(NSInteger)tag {
    
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
   
    textField.background = [UIImage imageNamed:@"textfield-1"];
    textField.textAlignment = NSTextAlignmentRight;
    textField.textColor =  textColor;
    textField.font = textFont;
    textField.tag = tag;

    textField.attributedPlaceholder = [self textFieldAttributedPlaceholderWith:textField placeholder:placeholder placeholderFont:placeholderFont];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 80, 48)];
    leftView.backgroundColor = [UIColor whiteColor];
    
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 80, 48)];
    nameLb.text = leftTitle;
    nameLb.textColor = kColorRGB(102,102,102);
    nameLb.font = kBaseFont_(14);
    nameLb.textAlignment = NSTextAlignmentLeft;
    [leftView addSubview:nameLb];
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    
    textField.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 15, 48)];
    textField.rightViewMode = UITextFieldViewModeAlways;
    
    textField.delegate = obj;
    [inView addSubview:textField];
    return textField;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    
    [self.nameTf resignFirstResponder];
    
    [self.cardTf resignFirstResponder];
    
    
}



- (void)nextBtnClick:(UIButton *)nextBtn {
    
    [self requestData];
    
}

- (void)requestData {
    
    NSString *idNumber = [[self.cardTf.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
     NSString *realName = [[self.nameTf.text stringByReplacingOccurrencesOfString:@" " withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSDictionary * param = @{@"method":@"verifyId",@"idNumber":idNumber,@"realName":realName};
    if (![ZHRTBasicMethod checkIdentityCardNo:idNumber]) {
         [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"身份证验证错误" view:self.view];
    } else if (![ZHRTBasicMethod isChinese:realName]) {
         [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"姓名验证错误" view:self.view];
        
    } else {
    
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject) {
        

        if ([responseObject[@"code"] isEqualToString:@"100000"]) {
            
            NSDictionary * params = @{@"method":@"getAccountStatus"};
            [AFHTTPSessionManager POSTWithParams:params success:^(NSURLSessionDataTask *task, id responseObject) {
                
                if ([responseObject[@"code"] isEqualToString:@"100000"]) {
                    NSDictionary *dic = responseObject[@"result"];
                    NSLog(@"%@", dic[@"verifiedStatus"]);
                    if ([dic[@"verifiedStatus"] isEqualToString:@"N"]) {
                        
                        XDVerifiedViewController *verified = [[XDVerifiedViewController alloc] init];
                        
                        [self.navigationController pushViewController:verified animated:YES];
                    } else if ([dic[@"safePassStatus"] isEqualToString:@"N"]) {
                        
                        XDSetSafePassViewController *setSafe = [[XDSetSafePassViewController alloc] init];
                        [self.navigationController pushViewController:setSafe animated:YES];
                        
                    } else if ([dic[@"bindStatus"] isEqualToString:@"N"]) {
                        
                        NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
                        if ([df valueForKey:@"toWithdraw"]) {
                            XDToWithdrawViewController *toWithdraw = [[XDToWithdrawViewController alloc] init];
                            [self.navigationController pushViewController:toWithdraw animated:YES];
                        } else {
                            
                            XDBindBankCardViewController *bindBankCard = [[XDBindBankCardViewController alloc] init];
                            [self.navigationController pushViewController:bindBankCard animated:YES];
                        }
                        
                    }
                }  else {
                    [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
                }
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"无网络" view:self.view];
            }];

            
            
            
            
        } else if ([responseObject[@"code"] isEqualToString:@"100001"]){ // 超时
            
            
        } else {
            
            [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
        
    }
    
}

- (void)agreeBtnClick: (UIButton *)btn {
    
    btn.selected = !btn.selected;
    if (self.nameTf.text.length > 0 && self.cardTf.text.length > 14 && self.agreeBtn.selected) {
        self.nextBtn.enabled = YES;
    } else {
        self.nextBtn.enabled = NO;
    }
}


- (void) xindaiBtnClick {
    
    
    NSLog(@"《新贷联盟实名认证协议》");
    
}

@end
